<template>
  <div class="master-page-wrapper">
    <div class="master-content m-layout" draggable="true" ref="masterContent">
      <h2>左</h2>
      <div>右</div>
    </div>
  </div>
</template>

<script setup lang="ts">
/* 
要点：
      HTML元素设置 `draggable="true"` 
      CSS设置 `cursor: move` 和 `poasition: absolute`
      JS监听 `dragstart` 和 `dragend` 事件，
*/

import { useTemplateRef, onMounted } from 'vue';

const masterContentRef = useTemplateRef('masterContent');

const startY = ref(0);
const startX = ref(0);
const initTop = ref(0);
const initLeft = ref(0);

onMounted(() => {
  // 获取元素的初始位置
  const rect = masterContentRef.value?.getBoundingClientRect();
  initTop.value = rect?.top || 0;
  initLeft.value = rect?.left || 0;

  // 监听拖拽
  if (masterContentRef.value) {
    masterContentRef.value.addEventListener('dragstart', (e) => {
      // 阻止默认的拖拽行为
      e.dataTransfer?.setData('text/plain', '');
      // 记录拖拽的起始位置
      startY.value = e.screenY;
      startX.value = e.screenX;
    });
    masterContentRef.value.addEventListener('dragend', (e) => {
      // 计算最终移动的距离
      const moveY = e.screenY - startY.value;
      const moveX = e.screenX - startX.value;
      masterContentRef.value!.style.left = initLeft.value + moveX + 'px';
      masterContentRef.value!.style.top = initTop.value + moveY + 'px';
    });
  }
});
</script>

<style scoped>
.master-page-wrapper {
  position: relative;
  line-height: 62px;
  height: 62px;
  border: 1px solid #e5e7eb;
  box-shadow: inset 0 -1px 0 #f3f3f4;

  .master-content {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    cursor: move;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
